package apacheshiro.controller;

import apacheshiro.model.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
public class ShiroController {

    /**
     * 需要权限访问
     * @return
     */
    @RequestMapping(value = "/adminhi")
    @ResponseBody
    public String hi(){
        return "hi";
    }

    /**
     * 登录页
     * @return
     */
    @RequestMapping(value = "/login")
    @ResponseBody
    public String login(){
        return "login";
    }

    /**
     * 模拟登录
     * @param user name=abc,password=123, customRealm设置AuthenticationInfo,可以使用postman，post，body选x-www-form-urlencoded
     * @return
     */
    @RequestMapping(value = "/dologin")
    @ResponseBody
    public String doLogin(User user){
        System.out.println(user.getName()+" "+user.getPassword());
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(user.getName(),user.getPassword());
        usernamePasswordToken.setRememberMe(true);
        subject.login(usernamePasswordToken);
        return "doLogin";
    }

    /**
     * 登出
     * @param request
     * @param response
     */
    @RequestMapping(value = "/out")
    @ResponseBody
    public String out(HttpServletRequest request, HttpServletResponse response){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "out";
    }

    /**
     * 权限访问,customRealm设置,AuthorizationInfo
     * @param request
     * @param response
     */
    @RequestMapping(value = "/role")
    @ResponseBody
    public void test(HttpServletRequest request, HttpServletResponse response){
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()){
            System.out.println("isAuthenticated");
            if (subject.hasRole("admin")){
                System.out.println("hasRole admin");
                if (subject.isPermitted("modify")){
                    System.out.println("isPermitted modify");
                }
            }
        }else{
            System.out.println("not authenticated");
        }
    }
}
